package lib.self.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;
import android.text.TextUtils;

import java.io.File;
import java.util.HashMap;

import lib.self.LogMgr;

/**
 * description: Intent工具类
 * author: Steven Xiao
 * date: 2017/8/10
 */
public class IntentUtil {

    private static final String TAG = IntentUtil.class.getSimpleName();

    private static HashMap<String, String> KMIMETypeMap = new HashMap<String, String>() {
        {
            put(".3gp", "video/3gpp");
            put(".apk", "application/vnd.android.package-archive");
            put(".asf", "video/x-ms-asf");
            put(".avi", "video/x-msvideo");
            put(".bin", "application/octet-stream");
            put(".bmp", "image/bmp");
            put(".c", "text/plain");
            put(".class", "application/octet-stream");
            put(".conf", "text/plain");
            put(".cpp", "text/plain");
            put(".doc", "application/msword");
            put(".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            put(".xls", "application/vnd.ms-excel");
            put(".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            put(".exe", "application/octet-stream");
            put(".gif", "image/gif");
            put(".gtar", "application/x-gtar");
            put(".gz", "application/x-gzip");
            put(".h", "text/plain");
            put(".htm", "text/html");
            put(".html", "text/html");
            put(".jar", "application/java-archive");
            put(".java", "text/plain");
            put(".jpeg", "image/jpeg");
            put(".jpg", "image/jpeg");
            put(".js", "application/x-javascript");
            put(".log", "text/plain");
            put(".m3u", "audio/x-mpegurl");
            put(".m4a", "audio/mp4a-latm");
            put(".m4b", "audio/mp4a-latm");
            put(".m4p", "audio/mp4a-latm");
            put(".m4u", "video/vnd.mpegurl");
            put(".m4v", "video/x-m4v");
            put(".mov", "video/quicktime");
            put(".mp2", "audio/x-mpeg");
            put(".mp3", "audio/x-mpeg");
            put(".mp4", "video/mp4");
            put(".mpc", "application/vnd.mpohun.certificate");
            put(".mpe", "video/mpeg");
            put(".mpeg", "video/mpeg");
            put(".mpg", "video/mpeg");
            put(".mpg4", "video/mp4");
            put(".mpga", "audio/mpeg");
            put(".msg", "application/vnd.ms-outlook");
            put(".ogg", "audio/ogg");
            put(".pdf", "application/pdf");
            put(".png", "image/png");
            put(".pps", "application/vnd.ms-powerpoint");
            put(".ppt", "application/vnd.ms-powerpoint");
            put(".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
            put(".prop", "text/plain");
            put(".rc", "text/plain");
            put(".rmvb", "audio/x-pn-realaudio");
            put(".rtf", "application/rtf");
            put(".sh", "text/plain");
            put(".tar", "application/x-tar");
            put(".tgz", "application/x-compressed");
            put(".txt", "text/plain");
            put(".wav", "audio/x-wav");
            put(".wma", "audio/x-ms-wma");
            put(".wmv", "audio/x-ms-wmv");
            put(".wps", "application/vnd.ms-works");
            put(".xml", "text/plain");
            put(".z", "application/x-compress");
            put(".zip", "application/x-zip-compressed");
            put("", "*/*");
        }
    };

    /**
     * 打开文件
     */
    public static void openFileByThird(Context context, String fileName) {
        File file = new File(fileName);
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //设置intent的Action属性
        intent.setAction(Intent.ACTION_VIEW);
        //获取文件file的MIME类型
        String type = getMIMEType(fileName);
        LogMgr.d(TAG, type);
        //设置intent的data和Type属性。
        Uri uri = null;
        if (VERSION.SDK_INT >= VERSION_CODES.N) {
            //判断版本是否在7.0以上
            uri = FileProvider.getUriForFile(context,
                    context.getPackageName(),
                    file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            uri = Uri.fromFile(file);
        }
        intent.setDataAndType(uri, type);

        //跳转
        try {
            context.startActivity(intent);
        } catch (Exception e) {
            ToastUtil.showToast(context, "未找到合适应用打开附件");
        }
    }

    /**
     * 根据文件后缀名获得对应的MIME类型。
     *
     * @param fileName
     */
    public static String getMIMEType(String fileName) {

        String type = "*/*";
        //获取后缀名前的分隔符"."在fName中的位置。
        int dotIndex = fileName.lastIndexOf(".");
        if (dotIndex < 0) {
            return type;
        }
        /* 获取文件的后缀名*/
        String end = fileName.substring(dotIndex, fileName.length()).toLowerCase();
        if (TextUtils.isEmpty(end)) {
            return type;
        }
        type = KMIMETypeMap.get(end);
        return type;
    }

    /**
     * 通过url打开外部浏览器
     */
    public static void openBrowser(Context context, String url) {
        try {
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri content_uri = Uri.parse(url);
            intent.setData(content_uri);
            context.startActivity(intent);
        } catch (Exception e) {
            LogMgr.e(TAG, e.toString());
        }
    }

    /**
     * 打开通知公告界面
     */
    public static void openNotifySetting(Context context) {
        Intent intent = new Intent();
        if (VERSION.SDK_INT > VERSION_CODES.O) {//android 8.0引导
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("android.provider.extra.APP_PACKAGE", context.getPackageName());
        } else if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP && VERSION.SDK_INT < VERSION_CODES.O) {//android 5.0-7.0
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("app_package", context.getPackageName());
            intent.putExtra("app_uid", context.getApplicationInfo().uid);
        } else {//其他
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", context.getPackageName(), null));
        }

        context.startActivity(intent);
    }

    /**
     * 直播拨打电话
     */
    @SuppressLint("MissingPermission")
    public static void callPhone(Context context, String phone) {
        Intent intent = new Intent(Intent.ACTION_CALL);
        Uri uri = Uri.parse("tel:" + phone);
        intent.setData(uri);
        context.startActivity(intent);
    }

    /**
     * 安装Apk
     *
     * @param activity
     * @param pathName
     */
    public static void installApk(Activity activity, @NonNull String pathName) {
        Intent install = new Intent(Intent.ACTION_VIEW);
        install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        File apkFile = new File(pathName);

        Uri uri;
        if (VERSION.SDK_INT >= VERSION_CODES.N) {
            install.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            uri = FileProvider.getUriForFile(activity, DeviceUtil.getAppPackageName(activity), apkFile);
        } else {
            uri = Uri.fromFile(apkFile);
        }
        install.setDataAndType(uri, "application/vnd.android.package-archive");
        activity.startActivity(install);
    }
}
